import { upLoadJsFile } from "@ap/tools/compile";
import path from "path";
import * as vscode from "vscode";
import { showInformationMessage, showErrorMessage } from "../vscode/message";

export async function upLoadJsFileType(e: { fsPath: string; path: string }) {
  if (!e) {
    const editor = vscode.window.activeTextEditor;
    if (editor) {
      const document = editor.document;
      e = {
        fsPath: document.uri.fsPath,
        path: document.uri.path,
      };
    } else {
      return "没有活动的编辑器可用。";
    }
  }
  const fileName = path.parse(e.fsPath).name;
  const fileExt = path.extname(e.fsPath);
  let isServerFile: boolean | undefined = await determineFileType(
    fileName + ".js",
    e.path,
  );
  if (isServerFile === undefined) {
    return "无法自动检测文件类型，请手动选择文件类型。";
  }
  if (isServerFile === true && fileExt === ".mjs") {
    showInformationMessage(
      "当前js文件为 ESM 模块，无法上传至服务端，请使用 CJS 模块上传",
    );
    return "当前js文件为 ESM 模块，无法上传至服务端，请使用 CJS 模块上传";
  }
  if (isServerFile === false && fileExt === ".cjs") {
    showInformationMessage(
      "当前js文件为 CJS 模块，无法上传至客户端，请使用 ESM 模块上传",
    );
    return "当前js文件为 CJS 模块，无法上传至客户端，请使用 ESM 模块上传";
  }
  const result = await upLoadJsFile(isServerFile, e.fsPath, fileName + ".js");

  if (result instanceof Error) {
    showErrorMessage(result.message);
    return result.message;
  } else if (result) {
    showInformationMessage(
      fileName +
        ".js 文件上传成功（" +
        (isServerFile ? "服务端" : "客户端") +
        "）",
    );
    return result;
  }
}

interface ExtendedQuickPickItem extends vscode.QuickPickItem {
  id: boolean;
}
export const item: ExtendedQuickPickItem[] = [
  {
    label: "服务端脚本（Server）",
    id: true,
  },
  {
    label: "客户端脚本（Client）",
    id: false,
  },
];

async function getFileType(): Promise<boolean | undefined> {
  const selectedOption = await vscode.window.showQuickPick(item, {
    title: "上传js文件：类型自动检测失败，请手动选择文件类型",
    matchOnDescription: true,
    canPickMany: false,
  });

  if (selectedOption) {
    return selectedOption.id;
  }
  return;
}

async function determineFileType(
  fileName: string,
  filePath: string,
): Promise<boolean | undefined> {
  if (fileName.includes("_server") || filePath.includes("/server/")) {
    return true;
  } else if (fileName.includes("_client") || filePath.includes("/client/")) {
    return false;
  } else {
    try {
      return await getFileType();
    } catch (error) {
      return undefined;
    }
  }
}
